package com.example.opengldemo._07_texture;

import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLSurface;
import android.opengl.GLES30;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.Surface;
import android.view.View;

import com.example.opengldemo.R;
import com.example.opengldemo.util.MatrixState;
import com.example.opengldemo.util.TextureUtil;
public class GLRenderer extends HandlerThread {

    private static final String TAG = "GLThread";
    //三大将 配置 显示 上下文
    private EGLConfig eglConfig = null;
    private EGLDisplay eglDisplay = EGL14.EGL_NO_DISPLAY;
    private EGLContext eglContext = EGL14.EGL_NO_CONTEXT;

    private int program;
    private int vPosition;
    private int uColor;
    private View view;

    public GLRenderer(View view) {
        super("GLRenderer");
        this.view = view ;
    }

    public void createEGL(){
        // 获取显示设备(默认的显示设备)
        eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
        // 初始化
        int []version = new int[2];
        //初始化显示设备
        if (!EGL14.eglInitialize(eglDisplay, version,0,version,1)) {
            throw new RuntimeException("EGL error "+EGL14.eglGetError());
        }
        // 获取FrameBuffer格式和能力
        int []configAttribs = {
                EGL14.EGL_BUFFER_SIZE, 32, //缓存大小
                EGL14.EGL_ALPHA_SIZE, 8,   // 透明度 8
                EGL14.EGL_BLUE_SIZE, 8,     // 三原色占 24
                EGL14.EGL_GREEN_SIZE, 8,
                EGL14.EGL_RED_SIZE, 8,
                EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
                EGL14.EGL_SURFACE_TYPE, EGL14.EGL_WINDOW_BIT,
                EGL14.EGL_NONE
        };
        //初始化EGL配置
        int []numConfigs = new int[1];
        EGLConfig[] configs = new EGLConfig[1];
        if (!EGL14.eglChooseConfig(eglDisplay, configAttribs,0, configs, 0,configs.length, numConfigs,0)) {
            throw new RuntimeException("EGL error "+EGL14.eglGetError());
        }
        //获取配置好的索引
        eglConfig = configs[0];

        // 创建OpenGL上下文
        int []contextAttribs = {
                EGL14.EGL_CONTEXT_CLIENT_VERSION, 3,
                EGL14.EGL_NONE
        };
        eglContext = EGL14.eglCreateContext(eglDisplay, eglConfig, EGL14.EGL_NO_CONTEXT, contextAttribs,0);
        if(eglContext== EGL14.EGL_NO_CONTEXT) {
            throw new RuntimeException("EGL error "+EGL14.eglGetError());
        }
        TextureImage image = new TextureImage(view) ;
        id = TextureUtil.getTextureId(view , R.drawable.android_robot0 , null , false) ;
    }
    int id  ;
    TextureImage image ;
    /**
     * 销毁OpenGL环境
     */
    private void destroyGL(){
        EGL14.eglDestroyContext(eglDisplay, eglContext);
        eglContext = EGL14.EGL_NO_CONTEXT;
        eglDisplay = EGL14.EGL_NO_DISPLAY;
    }
    @Override
    public synchronized void start() {
        super.start();

        new Handler(getLooper()).post(new Runnable() {
            @Override
            public void run() {
                createEGL();
            }
        });
    }

    public void release(){
        new Handler(getLooper()).post(new Runnable() {
            @Override
            public void run() {
                destroyGL();
                quit();
            }
        });
    }



    public void render(Surface surface, int width, int height){
        final int[] surfaceAttribs = { EGL14.EGL_NONE };
        EGLSurface eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0);
        EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
        init();
        change( width,  height) ;
        draw() ;
        EGL14.eglSwapBuffers(eglDisplay, eglSurface);
        EGL14.eglDestroySurface(eglDisplay, eglSurface);
    }

    private void draw() {
        GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
        image.drawSelf(id);
    }

    private void init() {
        GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1f);
        GLES30.glEnable(GLES30.GL_DEPTH_TEST);
        MatrixState.setInitStack();
        image = new TextureImage(view) ;
        id = TextureUtil.getTextureId(view , R.drawable.android_robot0 , null , false) ;
    }

    public void change(int width, int height){
        GLES30.glViewport(0, 0, width, height);
        float ratio = (float) width / height;
        MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 1, 10);
        MatrixState.setCamera(0, 0, 2f, 0, 0, 0f, 0f, 1.0f, 0.0f);
    }


}
